package com.jjwxc.jwjskandriod.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.jjwxc.jwjskandriod.BuildConfig;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.adapter.MainFragmentAdapter;
import com.jjwxc.jwjskandriod.config.BaseActivity;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.fragment.StackFragment;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.utils.PreUtils;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.framework.widget.RoundView;
import com.jjwxc.jwjskandriod.model.response.UpgradeVersionResponse;
import com.jjwxc.jwjskandriod.widget.PopViewUtil;
import com.jjwxc.jwjskandriod.widget.dialog.UpgradeVersionDialogFragment;

import java.util.Calendar;

public class MainActivity extends BaseActivity {

    /**
     * 菜单标题
     */
    private final String[] TAB_TITLES = new String[]{"书架", "推荐", "书库", "我的"};
    /**
     * 菜单图标
     */
    private final int[] TAB_IMGS = new int[]{R.drawable.bookshelf_main_tab, R.drawable.suggest_main_tab, R.drawable.stack_main_tab, R.drawable.my_main_tab};
    ViewPager viewPager;
    TabLayout tabLayout;
    /**
     * 页卡适配器
     */
    private MainFragmentAdapter adapter;
    private long firstTime = 0;
    //广播的code
    public static String RefreshMy = "MY_DATA";
    public static String RefreshSuggest = "Suggest_DATA";
    public static String RefreshStack = "Stack_DATA";

    @Override
    public int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void findView() {
        setNoTitle();
        viewPager = findViewById(R.id.view_pager);
        tabLayout = findViewById(R.id.tab_layout);
    }


    @Override
    public void setListener() {

    }

    @Override
    public void afterCreate() {
        upgradeVersion();

        // 初始化页卡
        initPager();
        setTabs(tabLayout, getLayoutInflater(), TAB_TITLES, TAB_IMGS);

        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(RefreshMy);
        myIntentFilter.addAction(RefreshSuggest);
        myIntentFilter.addAction(RefreshStack);
        registerReceiver(mBroadcastReceiver, myIntentFilter);
        viewPager.setCurrentItem(1);
        viewPager.setOffscreenPageLimit(4);
        tabLayout.getTabAt(1).select();
        String type = getIntent().getStringExtra("TYPE");
        if (!StUtils.isEmpty(type)) {
            viewPager.setCurrentItem(2);
            tabLayout.getTabAt(2).select();
            StackFragment fragment = ((StackFragment) getFragemtn(adapter.getFragmentManager(), R.id.view_pager, 2));
            fragment.setMonthState();
        }

        if (BuildConfig.DEBUG) {
            RoundView.getInstance().showRoundView(this, () -> startActivity(new Intent(MainActivity.this, RequestLogger.class)));
        }
    }

    /**
     * 判斷版本是否需要更新
     */
    private void upgradeVersion() {
        get(Url.upgradeVersion, null, UpgradeVersionResponse.class, new FFNetWorkCallBack<UpgradeVersionResponse>() {
            @Override
            public void onSuccess(UpgradeVersionResponse response) {
                // 需要添加判断，何时出现弹窗
                int isUpgrade = response.getData().getCode().compareTo(getVerName(MainActivity.this));
                if (isUpgrade <= 0) {
                    return;
                }

                // 自定义更新弹窗
                UpgradeVersionDialogFragment upgradeVersionDialogFragment = new UpgradeVersionDialogFragment();

                if (response.getData().getUpgradeType() == 1) {       //  1 建議更新  2 强制更新
                    upgradeVersionDialogFragment.setShowCancel(true);
                }

                upgradeVersionDialogFragment.setGravity(Gravity.CENTER);
                upgradeVersionDialogFragment.setCancelable(false);
                upgradeVersionDialogFragment.confirmCallback = () -> {
                    gotoDownload(response.getData().getUrl());
                    return null;
                };

                upgradeVersionDialogFragment.show(getSupportFragmentManager(), "UpgradeVersionDialogFragment");
            }

            @Override
            public boolean onFail(UpgradeVersionResponse response) {
                return false;
            }
        });
    }

    /**
     * 跳转到下载地址
     */
    private void gotoDownload(String url) {
        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra("WEB_URL", url);
        startActivity(intent);
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(RefreshMy)) {
                String msg = intent.getStringExtra(RefreshMy);
                e("接受到消息jsk:" + action + "--:" + msg);
                viewPager.setCurrentItem(3);
                tabLayout.getTabAt(3).select();
            } else if (action.equals(RefreshSuggest)) {
                String msg = intent.getStringExtra(RefreshSuggest);
                e("接受到消息jsk:" + action + "--:" + msg);
                viewPager.setCurrentItem(1);
                tabLayout.getTabAt(1).select();
            } else if (action.equals(RefreshStack)) {
                String msg = intent.getStringExtra(RefreshStack);
                e("接受到消息jsk:" + action + "--:" + msg);
                viewPager.setCurrentItem(2);
                tabLayout.getTabAt(2).select();
                StackFragment fragment = ((StackFragment) getFragemtn(adapter.getFragmentManager(), R.id.view_pager, 2));
                fragment.setMonthState();
            }
        }

    };

    /**
     * 设置页卡显示效果
     *
     * @param tabLayout
     * @param inflater
     * @param tabTitlees
     * @param tabImgs
     */
    private void setTabs(TabLayout tabLayout, LayoutInflater inflater, String[] tabTitlees, int[] tabImgs) {
        for (int i = 0; i < tabImgs.length; i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            View view = inflater.inflate(R.layout.item_main_menu, null);
            // 使用自定义视图，目的是为了便于修改，也可使用自带的视图
            tab.setCustomView(view);
            TextView tvTitle = (TextView) view.findViewById(R.id.txt_tab);
            tvTitle.setText(tabTitlees[i]);
            ImageView imgTab = (ImageView) view.findViewById(R.id.img_tab);
            imgTab.setImageResource(tabImgs[i]);
            tabLayout.addTab(tab);
        }
    }

    private void initPager() {
        adapter = new MainFragmentAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);

        // 关联切换
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 取消平滑切换
                viewPager.setCurrentItem(tab.getPosition(), false);
                Calendar calendar = Calendar.getInstance();//取得当前时间的年月日 时分秒
                int month = calendar.get(Calendar.MONTH) + 1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                String time = month + ":" + day;
                String oldTime = PreUtils.getString("TIME_Q", "");

                //青少年模式 登录了和我的
                if ((StUtils.isEmpty(oldTime) && tab.getPosition() == 3)
                        || (!oldTime.equals(time) && PreUtils.getString("RefreshToken", null) != null
                        && tab.getPosition() == 3)) {
                    PreUtils.setString("TIME_Q", time);
                    PopViewUtil.adolescentPop(tabLayout, MainActivity.this);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                showToast("再按一次退出程序");
                firstTime = secondTime;
                return true;
            } else {
                finish();
            }
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    public Fragment getFragemtn(FragmentManager fragmentManager, int viewId, long id) {
        return fragmentManager.findFragmentByTag("android:switcher:" + viewId + ":" + id);
    }

    /**
     * 獲取版本號名稱
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "1.0.0";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }
}
